#include <iostream>
#include <unistd.h>
#include <string>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;

int main()
{
    //1、创建管道
    int fds[2] = {0};
    int n = pipe(fds);
    if (n != 0)
    {
        cerr << "pipe error" << endl;
        return 1;
    }

    //2、创建子进程
    pid_t id = fork();
    if (id < 0)
    {
        cerr << "fork error" << endl;
        return 2;
    }
    else if (id == 0)
    {
        //子进程
        //3、关闭不需要的fd
        close(fds[0]);//0是读
        int cnt = 0;
        while (true)
        {
            string message = "hello world, hello ";
            message += to_string(getpid());
            message += ", ";
            message += to_string(cnt++);
            write(fds[1], message.c_str(), message.size());
            sleep(1);
            break;
        }
        //sleep(1);
        exit(0);
    }
    else
    {
        //父进程
        close(fds[1]);//1是写
        char buffer[1024];
        while (true)
        {
            ssize_t n = read(fds[0], buffer, 1024);
            if (n > 0)
            {
                buffer[n] = 0;
                cout << "child->father, message: " << buffer << endl;
            }
            else
            {
                cout << "child quit" << endl;
                //break;
            }
            close(fds[0]);
            //break;
        }

        int status = 0;
        pid_t rid = waitpid(id, &status, 0);
        if (rid > 0)
        {
            cout << "father wait child success, id :" << rid << "  exit code:" << 
            ((status<<8)&0xFF) << "  exit signal: " << (status&0x7F) << endl;
        }
    }
    return 0;
}
